package Leetcode.ArrayAndLinkedList.hasCycle141;


/**
 * 判断链表是否有环
 * 快慢指针法
 * 方案较为简单 不做注解
 */

/**
 * 次数 2
 */

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null) {
            return false;
        }
        ListNode prev = head;
        ListNode next = head.next;
        while(next != null && next.next != null) {
            prev = prev.next;
            next = next.next.next;
            if(next == prev) {
                return true;
            }
        }
        return false;
    }
}










/**
 * public boolean hasCycle(ListNode head) {
 * if(head == null) {
 * return false;
 * }
 * ListNode slow = head;
 * ListNode fast = head.next;
 * <p>
 * while(fast != null && fast.next !=null) {
 * <p>
 * if(fast.equals(slow)) {
 * return true;
 * }
 * fast = fast.next.next;
 * slow = slow.next;
 * }
 * return false;
 * }
 */
